package cn.aeolia.Interceptor;

import cn.aeolia.utils.I18nUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

public class LoginHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //默认登录页面直接通过不拦截
        String servletPath = request.getServletPath();
        if (servletPath == "/" || servletPath.equals("/")) {
            return true;
        }
        //获取session，看其中是否有已经登录的用户
        Object loginUser = request.getSession().getAttribute("loginUser");
        if (null == loginUser) {
            //没有已经登录的用户则提示没有访问权限
            request.setAttribute("msg", I18nUtils.getValue("login.msg_noAccessGrant"));
            request.getRequestDispatcher("/login?lang="+ Locale.getDefault()).forward(request, response);
            return false;
        } else {
            //有已登录的用户则不拦截
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
